package com.adee.gulimall.common.advice;

import com.adee.gulimall.util.exception.BizCodeEnum;
import com.adee.gulimall.util.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@Slf4j
//@ResponseBody
@RestControllerAdvice(basePackages = {
        "com.adee.gulimall.coupon.controller",
        "com.adee.gulimall.member.controller",
        "com.adee.gulimall.order.controller",
        "com.adee.gulimall.product.app",
        "com.adee.gulimall.search.controller",
        "com.adee.gulimall.thirdparty.controller",
        "com.adee.gulimall.ware.controller"
})
public class ExceptionControllerAdvice {

    // 全局拦截并处理校验类型异常，并返回异常响应
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e) {
        log.error("数据校验出现问题{}，异常类型{}", e.getMessage(), e.getClass());
        BindingResult result = e.getBindingResult();
        if (result.hasErrors()) {
            Map<String, String> map = new HashMap<>();
            result.getFieldErrors().forEach(err -> {
                map.put(err.getField(), err.getDefaultMessage());
            });
            return R.error(BizCodeEnum.ARG_INVALID_EXCEPTION).put("data", map);
        }
        return R.error(BizCodeEnum.UNKNOWN_EXCEPTION);
    }

    // 精确匹配不到的异常统一处理
    @ExceptionHandler
    public R handleException(Throwable e) {
        log.error(e.toString(), e);
        return R.error(BizCodeEnum.UNKNOWN_EXCEPTION);
    }
}
